package sf.core.service.impl;

import javax.annotation.Resource;

import com.qiniu.util.Auth;
import com.qiniu.util.StringMap;

import sf.core.mapper.TfImageMapper;
import sf.core.service.StorageService;

public class QiniuStorageService implements StorageService {

	@Resource
	private TfImageMapper imageMapper;

	private String accesskey;
	private String secretkey;
	private String imageTokenUrl;
	private String avatarTokenUrl;

	public String getAccesskey() {
		return accesskey;
	}

	public void setAccesskey(String accesskey) {
		this.accesskey = accesskey;
	}

	public String getSecretkey() {
		return secretkey;
	}

	public void setSecretkey(String secretkey) {
		this.secretkey = secretkey;
	}

	public String getImageTokenUrl() {
		return imageTokenUrl;
	}

	public void setImageTokenUrl(String imageTokenUrl) {
		this.imageTokenUrl = imageTokenUrl;
	}

	public String getAvatarTokenUrl() {
		return avatarTokenUrl;
	}

	public void setAvatarTokenUrl(String avatarTokenUrl) {
		this.avatarTokenUrl = avatarTokenUrl;
	}

	private Auth auth;

	public Auth getAuth() {
		if (auth == null) {
			auth = Auth.create(accesskey, secretkey);
		}
		return auth;
	}

	public String getUploadImageToken() {
		return getAuth().uploadToken(BUCKET_MEDIA);
	}

	public String getUploadImageToken(int type, int xid) {
		StringMap policy = fetchKeyPolicy(imageTokenUrl, String.format("key=$(key)&type=%s&xid=%s", type, xid));
		return getAuth().uploadToken(BUCKET_MEDIA, null, 3600, policy, true);
	}

	public String getUploadAvatarToken(char avatarType, int xid) {

		StringMap policy = fetchKeyPolicy(avatarTokenUrl, String.format("key=$(key)&type=%s&xid=%s", avatarType, xid));
		return getAuth().uploadToken(BUCKET_MEDIA, null, 3600, policy, true);
	}

	private StringMap fetchKeyPolicy(String url, String body) {
		StringMap policy = new StringMap();
		policy.put("callbackUrl", url);
		policy.put("callbackFetchKey", 1);
		policy.put("callbackBody", body);
		return policy;
	}

}
